<?php


namespace app\manager\controller;


use app\common\controller\Common;
use app\common\model\PayOrder;
use app\common\model\SharingOrder;
use app\common\model\SharingReceiver;
use think\Db;
use think\facade\App;
use think\facade\Log;
use Wxpay\WxProfitsharing;

//分账控制器
class Sharing extends Common
{
    public function listsSharingOrder()
    {
        if ($this->request->isAjax()) {
            $page = $this->getPage();
            $pagesize = $this->getPageSize();
            $min = ($page - 1) * $pagesize;
            $max = $pagesize;
            $count = SharingOrder::count();
            $sql = "SELECT * FROM sharing_order limit " . $min . "," . $max;
            $reSharing = Db::query($sql);
            if (count($reSharing) == 0) return $this->errJson('暂无返回记录');
            return $this->listJson($reSharing, $count);
        } else {

            return $this->fetch('order_lists');
        }
    }

    /**
     * 显示分账单详情
     * @return \think\response\Json|\think\response\View
     */
    public function show(){
        $shorid=request()->param('shorid');
        if (is_null($shorid)||$shorid=="") return $this->errJson('参数错误');
        $reSharingOrder = SharingOrder::get($shorid);
        if (empty($reSharingOrder)) return $this->errJson('数据异常');
        $this->assign('SharingOrder',$reSharingOrder);
        return view();
    }

    /**
     * 分账接收方列表
     *
     */
    public function listsSharingReceiver()
    {
        if ($this->request->isAjax()) {
            $limit = $this->getPageSize();
            $reSharingReceiver = SharingReceiver::paginate($limit);
            if (empty($reSharingReceiver)) return $this->errJson('暂无数据');
            return $this->listJson($reSharingReceiver->items(), $reSharingReceiver->total());
        } else {
            return $this->fetch('receiver_lists');
        }
    }

    /**
     * 分账操作前的 信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSharingOrder(){
        $shorid=request()->param('shorid');
        $merid=request()->param('merid');
        if (is_null($shorid)||$shorid==""||is_null($merid)||$merid=="") return $this->errJson('参数错误');
        //分账订单
        $reSharingOrder = SharingOrder::get($shorid);
        if (empty($reSharingOrder)) return $this->errJson('数据异常');
        $o_no=$reSharingOrder->order_o_no;//支付订单号
        $amount=$reSharingOrder->amount;//分账款金额
        $name = $reSharingOrder->name;//商家全称，或者个人真实姓名
        //SharingReceiver::where([''])->find();
        //商家信息
        $reMerchant = \app\common\model\Merchant::where(['merid'=>$merid,'sharing'=>2])->where('status','<>',-1)->find();
        if (empty($reMerchant)) return $this->errJson('商家信息与分账信息不匹配');
        $mername = $reMerchant->mername;//商家店名
        $retime = $reMerchant->retime;//注册时间
        $mobile = $reMerchant->mobile;//注册电话

        //支付订单信息
        $rePayOrder = PayOrder::where(['o_no'=>$o_no,'o_status'=>2])->find();
        if (empty($rePayOrder)) return $this->errJson('分账信息与订单信息不匹配');
        $total_fee = $rePayOrder->total_fee;//订单金额
        $pay_time = $rePayOrder->uptime;//订单支付时间
        $card_no = $rePayOrder->o_card_no;//会员卡号
        $datas=[
            'sharing_amount'=>$amount,//分账款金额
            'mername'=>$mername,//商家店名
            'name'=>$name,
            'mer_retime'=>$retime,//注册时间
            'mer_mobile'=>$mobile,//注册电话
            'total_fee'=>$total_fee,//订单金额
            'pay_time'=>$pay_time,//订单支付时间
            'card_no'=>$card_no //会员卡号
        ];
        return $this->okJson($datas);
    }

    /**
     * 添加分账接收弹窗接口
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {

        if ($this->request->isAjax()) {

        } else {
            $reMerchant = \app\common\model\Merchant::where(['status' => 2])->select();
            $this->assign('Merchant', $reMerchant);
            return view();
        }
    }

    /**
     * 添加分账接收方
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addreceiver()
    {
        $openid = request()->param('openid');
        $name = request()->param('name');//用户真实姓名，或者商家全称，微信会去验证真假
        $bill_type = request()->param('bill_type');//-1 固定金额，2比例
        $type = request()->param('type');//用户类型
        $amount = request()->param('amount');//分账金额
        $ratio = request()->param('ratio');//分账比率，是大不能超过0.3
        $meichantNO = request()->param('meichantNO');//商家商户号

        if (is_null($type) || $type == "") return $this->errJson('参错误');
        if (is_null($openid) || $openid == "") return $this->errJson('参错误');
        if (is_null($bill_type) || $bill_type == "") return $this->errJson('参错误');


        $reMer = \app\common\model\Merchant::where(['openid' => $openid, 'status' => 2])->find();
        if (empty($reMer)) return $this->errJson('参错误');
        $merid = $reMer->merid;
        $mername=$reMer->mername;
        $reSharing = SharingReceiver::where(['merid' => $merid, 'status' => 2])->find();
        if ($reSharing) return $this->errJson('已经添加过了');

        if ('PERSONAL_OPENID' == $type) {//如果是个人，传openid，
            $account = $openid;
        } elseif ('MERCHANT_ID' == $type) {//如果是商户，传商户号
            $account = $meichantNO;
        }

        $receiver = array(
            'type' => $type,
            'account' => $account,
            'name' => $name,
            'relation_type' => 'SERVICE_PROVIDER'
        );
        $Sharing = new WxProfitsharing();
        $ret = $Sharing->addreceiver($receiver);
        if ($ret['code'] == -1) return $this->errJson('添加失败->' . $ret['msg']);

        if ($bill_type == 2) {//按比例分账
            $amount = 0;
            if (!is_null($ratio) || $ratio != '') {
                if ($ratio > 0.3) {
                    return $this->errJson('分账比例超出有效范围');
                } elseif ($ratio <= 0) {
                    return $this->errJson('分账比例超出有效范围');
                }
            }
        } else {
            if (is_null($amount) || $amount == "" || $amount == 0) return $this->errJson('分账金额有错');
        }
        $data = [
            'merid' => $merid,
            'mername'=>$mername,//商家店名
            'account' => $openid,//这里是个人，所有用openid,如果商户，用商户号
            'amount' => $account,
            'name' => $name,//个人用真实姓名，商户，用商户全称
            'type' => $type,//个人PERSONAL_OPENID；商户MERCHANT_ID
            'ratio' => $ratio,
            'relation_type ' => 'SUPPLIER',
            'time' => time(),
            'meichant_no' => $meichantNO,
            'bill_type' => $bill_type,
            'status' => 2
        ];
        Db::startTrans();
        try {
            $retSharing = SharingReceiver::create($data);
            $reMer->sharing = 2;
            $reMer->updatetime = time();
            $reMer->save();
            if ($reMer->save() && $retSharing){
                Db::commit();
                return $this->okJson('成功');
            }
        }catch (\Exception $exception){
            Log::save();
            Db::rollback();
        }
    }

    /**
     * 发起单次发账
     */
    public function profitsharing()
    {
        $shorid = request()->param('shorid');
        $reSharingOrder = SharingOrder::get($shorid);
        if (!empty($reSharingOrder) && -1 == $reSharingOrder->status) {
            $amount = $reSharingOrder->amount;  //金额
            $transaction_id = $reSharingOrder->transaction_id; //微信支付订单号
            $out_order_no = $reSharingOrder->shor_no; //商户分账单号
            $type = $reSharingOrder->receivers_type; //分账类型
            $account = $reSharingOrder->account; //分账账号
            $description = $reSharingOrder->description; //描述
            $receivers = [];
            $receivers[] = array(
                'type' => $type,
                'account' => $account,
                'amount' => ntval($amount),
                'description' => $description
            );
            $Sharing = new WxProfitsharing();
            $ret = $Sharing->profitsharing($transaction_id, $out_order_no, $receivers);
            if ($ret['code'] == -1) return $this->errJson('分账失败->' . $ret['msg']);
            $reSharingOrder->status = 2;
            $reSharingOrder->updatetime = time();
        }

        return $this->errJson('数据异常');
    }

    /**
     * //删除分账接收方
     * @return \think\response\Json
     */
    public function removeReceiver(){
        $reid=request()->param('reid');
        if (is_null($reid)||$reid=="") return $this->errJson('参数错误');
        Db::startTrans();
        try {
            $reSharingReceiver = SharingReceiver::get($reid);
            if (empty($reSharingReceiver)) return $this->errJson('数据异常');
            $reSharingReceiver->status == -1;
            $reSharingReceiver->save();
            if ($reSharingReceiver->save()){
                $receiver = [
                    'type' => $reSharingReceiver->type,
                    'account' => $reSharingReceiver->account
                ];
                $Sharing = new WxProfitsharing();
                $ret = $Sharing->removereceiver($receiver);
                if ($ret['code'] == 2){
                    Db::commit();
                    return $this->okJson('删除成功');
                }else{
                    Db::rollback();
                    return $this->errJson('删除失败->' . $ret['msg']);
                }
            }
        }catch (\Exception $exception){
            Db::rollback();
            return $this->errJson('删除失败->');
        }
        return $this->errJson('删除失败->');
    }

    public function closeSharingOrder(){
        $shorid=request()->param('shorid');
        $note =request()->param('note');
        if (is_null($shorid)||$shorid=="") return $this->errJson('参数错误');
        if (is_null($note)||$note=="") return $this->errJson('请填写关单原因');
        $reSharingOrder = SharingOrder::get($shorid);
        if (empty($reSharingOrder)) return $this->errJson('数据异常');
        $reSharingOrder->status=-2;
        $reSharingOrder->note=$note;
        $reSharingOrder->updatetime=time();
        if($reSharingOrder->save()) return $this->okJson('关单成功');
        return $this->errJson('关单失败');
    }

}


